package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.oa.core.entity.com.Asset;
import com.fz.us.oa.core.entity.com.AssetFlit;
import com.fz.us.oa.core.entity.com.AssetMaintain;
import com.fz.us.oa.core.entity.com.AssetScrap;
import com.fz.us.oa.core.service.com.AssetService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/26.
 */
@Controller
@RequestMapping(value = "/com/asset")
public class AssetController extends BaseController {
    private static final long serialVersionUID = -4723388379645263123L;

    @Autowired
    private UserService userService;
    @Autowired
    private AssetService assetService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            Asset asset=assetService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("asset", asset);
        }
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/asset_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            Asset asset=assetService.get(keyId);
            if(asset.getNumStatus()>=1){
                TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
                int stepNo = taskEntity.getStepNo();
                String isEdit =  isEdit(keyId);
                model.addAttribute("stepNo", stepNo);
                model.addAttribute("isEdit", isEdit);
            }
            model.addAttribute("asset", asset);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/asset_read";
    }

    /**
     * 保存Model数据
     */
    private Asset saveModel(User user, String keyId, String assetNo, String name, String brand, String model) throws ParseException {

        Asset asset = null;
        if (StringUtils.isBlank(keyId)) {
            asset = new Asset();
            asset.setCreater(user);
            asset.setCompany(user.getCompany());
        } else {
            asset = assetService.get(keyId);
        }

        if (StringUtils.isNotBlank(assetNo)) {
            asset.setAssetNo(assetNo);
        }

        if (StringUtils.isNotBlank(name)) {
            asset.setName(name);
        }

        if (StringUtils.isNotBlank(brand)) {
            asset.setBrand(brand);
        }

        if (StringUtils.isNotBlank(model)) {
            asset.setModel(model);
        }
        return asset;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetNo, String name, String brand, String model) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Asset asset = saveModel(user,keyId,assetNo,name,brand,model);
        if(StringUtils.isNotEmpty(keyId)){
            assetService.update(asset);
            rMap.put("message", "更新成功");
        } else {
            assetService.save(asset, "com.fz.us.oa.core.entity.com.Asset");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetNo, String name, String brand, String model,
                         String curDutyId, String comment) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        Asset asset = saveModel(user,keyId,assetNo,name,brand,model);
        asset.setNumStatus(1);
        asset.setTxtStatus("流转中");

        if (StringUtils.isNotEmpty(keyId)) {//这个表单永远都是有keyID的

            TaskEntity taskEntity = taskEntityService.get(keyId);
            if(taskEntity == null){
                taskEntity = new TaskEntity();
                taskEntity.setCreater(user);
                taskEntity.setKeyId(keyId);
                taskEntity.setStepNo(1);
                taskEntity.setEntityName("com.fz.us.oa.core.entity.com.Asset");
                taskEntity.setProcessState(FlowEnum.ProcessState.Running);//如果一部归档改成Finished
                taskEntityService.save(taskEntity);
            }

            assetService.approve(asset, dutyService.get(curDutyId), comment);

            if(asset.getProcessState().name().equals("Finished")){
                asset.setTxtStatus("空闲");
                assetService.update(asset);
            }

        } else {
            assetService.commit(asset, "com.fz.us.oa.core.entity.com.Asset", dutyService.get(curDutyId));
        }
        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Asset asset=assetService.get(keyId);
        assetService.approve(asset, dutyService.get(curDutyId), comment);

        if(asset.getProcessState().name().equals("Finished")){
            asset.setTxtStatus("空闲");
            assetService.update(asset);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Asset asset=assetService.get(keyId);
            assetService.back(asset, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Asset asset=assetService.get(keyId);
            assetService.deny(asset, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
//        rules.add(RuleHelper.eq("processState", FlowEnum.ProcessState.Finished));
        rules.add(RuleHelper.eq("company", company));
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));

        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //待入库
//                rules.add(RuleHelper.eq("txtStatus", "待入库"));
                rules.add(RuleHelper.or(
                        RuleHelper.eq("txtStatus", "待入库"),
                        RuleHelper.eq("txtStatus", "流转中")
                ));

            }else if(viewtype.equals("2")){
                //资产明细
                rules.add(RuleHelper.eq("numStatus", 1));

            }else if(viewtype.equals("3")){
                //空闲资产
                rules.add(RuleHelper.eq("txtStatus", "空闲"));

            }else if(viewtype.equals("4")){
                //使用中资产
                rules.add(RuleHelper.eq("txtStatus", "使用中"));

            }
        }
//        searchResult = assetService.findPagingBySearch(null,rules,order);
        searchResult = assetService.paging(null, rules, order,
                "com.fz.us.oa.core.entity.com.Asset", new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed}, null);

        List<Asset> assetList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        DecimalFormat fnum = new DecimalFormat("##0.00");
        for(Asset asset: assetList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(asset.getId())?"":asset.getId());
            rMap.put("assetNo", asset.getAssetNo());
            rMap.put("name", asset.getName());
            rMap.put("brand", asset.getBrand());
            rMap.put("model", asset.getModel());
            rMap.put("purchaseMoney", fnum.format(asset.getPurchaseMoney()));

            rMap.put("userName", asset.getUserName());
            rMap.put("userDept", asset.getUseDepartment()==null?"": asset.getUseDepartment().getName());
            rMap.put("txtStatus", asset.getTxtStatus());
            rMap.put("datPurchase", asset.getDatPurchase()==null?"": DataUtil.DateToString(asset.getDatPurchase()));

//        rMap.put("processStateName", asset.getProcessState()==null?"": asset.getProcessState().value());
//        rMap.put("createTime", asset.getCreateTime()==null?"": DataUtil.DateTimeToString(asset.getCreateTime()));
//        rMap.put("dateApply", asset.getDateApply()==null?"": DataUtil.DateTimeToString(asset.getDateApply()));
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 选择资产(单个)
     */
    @RequestMapping(value = "dialogs", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialogs(@CurrentUser User user, Model model,@RequestParam() String category) {
        model.addAttribute("category", category);
        return "/com/asset_dialogs";
    }

    /**
     * 资产调拨
     */
    @RequestMapping(value = "flit/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String flit(@CurrentUser User user, Model model,
                       @PathVariable String keyId) {
        model.addAttribute("user",user);

        Asset asset = assetService.get(keyId);

        AssetFlit assetFlit = new AssetFlit();
        assetFlit.setCreater(user);
        assetFlit.setAsset(asset);
        assetFlit.setName(asset.getName());

        if (asset.getUseDepartment() != null) {
            assetFlit.setOldUseDeptName(asset.getUseDepartment().getName());
        }

        if (asset.getUser() != null) {
            assetFlit.setOldUserName(asset.getUser().getName());
        }

        model.addAttribute("assetFlit", assetFlit);
        return "/com/assetflit_input";
    }

    /**
     * 资产维护
     */
    @RequestMapping(value = "maintain/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String maintain(@CurrentUser User user, Model model,
                           @PathVariable String keyId) {
        model.addAttribute("user",user);

        Asset asset = assetService.get(keyId);

        AssetMaintain assetMaintain = new AssetMaintain();
        assetMaintain.setCreater(user);
        assetMaintain.setAsset(asset);
        assetMaintain.setName(asset.getName());
        assetMaintain.setNumStatus(0);

        model.addAttribute("assetMaintain",assetMaintain);
        return "/com/assetmaintain_input";
    }

    /**
     * 资产报废
     */
    @RequestMapping(value = "scrap/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String scrap(@CurrentUser User user, Model model,
                        @PathVariable String keyId) {
        model.addAttribute("user",user);

        ArrayList<DictItem> typeDict = getDictItems(user,"scrapReason");
        if(typeDict.size()>0){
            model.addAttribute("typeDict",typeDict);
        }

        Asset asset = assetService.get(keyId);

        AssetScrap assetScrap = new AssetScrap();
        assetScrap.setCreater(user);
        assetScrap.setAsset(asset);
        assetScrap.setName(asset.getName());

        model.addAttribute("assetScrap",assetScrap);
        return "/com/assetscrap_input";
    }


}
